<script setup lang="ts">
import { ref, reactive, unref } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import { ElLoading, ElTabs, ElTabPane } from 'element-plus'
import { ucTerminalRoleSeeApi, ucTerminalRoleSetApi } from '@/api/uc/set'
import { Table } from '@/components/Table'
import { Dialog } from '@/components/Dialog'
import Role from './components/Role.vue'
import { useTable } from '@/hooks/web/useTableTest'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
const saveLoading = ref(false) //保存中的状态
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

let tabValue = ref('1')
const terminal_type = dict.terminal_type
const getRoleList = async () => {
  const loadingMain = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const res = await ucTerminalRoleSeeApi({ terminal_type: tabValue.value })
    .catch(() => {})
    .finally(() => {
      setTimeout(() => {
        loadingMain.close()
      }, 500)
    })
  if (res) {
    tableObject.tableList = res.data
  }
}
const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: getRoleList,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList } = methods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'role_name',
    label: '角色',
    table: { show: true },
    form: { show: false }
  },
  {
    field: 'terminal_type',
    label: '所属类型',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('terminal_type', cellValue)
    }
  },
  {
    field: 'is_admin',
    label: '负责人',
    form: { show: true },
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('is', cellValue)
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

//初始化
const handleChange = () => {
  getRoleList()
}
const init = async () => {
  await getList()
}
init()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const actionType = ref('')
const action = async (type: string, row: any = {}) => {
  actionType.value = type
  console.log(row, 'row')
  switch (type) {
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }
      dialogVisible.value = true
      break
    default:
      console.log('未知类型')
  }
}
const addRef = ref<ComponentRef<typeof Role>>()
const save = async () => {
  const add = unref(addRef)
  switch (actionType.value) {
    case 'add':
      console.log(add, 'add')
      const data = (await add?.getForm()) as any
      dialogVisible.value = false
      data.list.forEach((element) => {
        element.is_admin = '0'
        element.terminal_type = tabValue.value
      })
      tableObject.tableList = concatObjArray(tableObject.tableList, data.list)
      console.log(tableObject.tableList, 'tableObject.tableList')
      break
    case 'save':
      const arrData = tableObject.tableList.map((element) => ({
        role_id: element.role_id,
        is_admin: element.is_admin
      }))
      // console.log(arrData, 'arrData')
      const res = await ucTerminalRoleSetApi({
        // tableObject.tableList
        terminal_type: tableObject.tableList[0].terminal_type,
        data: arrData
      })
        .catch(() => {})
        .finally(() => {
          // loading.value.save = false
        })
      console.log(res, 'res')
      break
    default:
  }
}
const changeSelect = (val, row) => {
  console.log(val, row)
  tableObject.tableList.forEach((element) => {
    console.log(element.role_id, 'element.role_id')
    if (element.role_id != row.role_id) {
      element.is_admin = '0'
    }
  })
}
const concatObjArray = (obj1, obj2) => {
  for (let key in obj2) {
    if (obj1.hasOwnProperty(key)) {
      if (Array.isArray(obj1[key] == 'role_id')) {
        obj2[key] = obj2[key].concat(obj1[key])
      }
    } else {
    }
  }
  return obj2
}
</script>

<template>
  <ContentWrap>
    <ElTabs v-model="tabValue" type="card" class="demo-tabs" @tab-change="handleChange">
      <ElTabPane
        :label="item.label"
        :name="item.value"
        v-for="(item, index) in terminal_type"
        :key="index"
      />
    </ElTabs>
    <div class="mb-10px text-right">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
      <ElButton type="primary" @click="save((actionType = 'save'))">保存</ElButton>
    </div>
    <Table
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :selection="false"
      :border="true"
      @register="register"
    >
      <template #is_admin="{ row }">
        <ElSelectV2
          v-model="row.is_admin"
          @change="changeSelect(row.is_admin, row)"
          :options="dict.is"
        />
      </template>
    </Table>
  </ContentWrap>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Role
      v-if="actionType == 'add'"
      :terminalType="tabValue"
      :list="tableObject.tableList"
      ref="addRef"
    />
    <template #footer>
      <ElButton v-if="actionType == 'add'" type="primary" :loading="saveLoading" @click="save()">
        保存
      </ElButton>
      <ElButton @click="dialogVisible = false">关闭</ElButton>
    </template>
  </Dialog>
</template>

<style lang="less" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  a {
    padding: 0 3px;

    i {
      margin-top: 5px;
    }
  }
}
</style>
